package sdu.icat.forum.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import sdu.icat.forum.service.GroupService;
import sdu.icat.forum.smodel.Group;
import sdu.icat.pj.base.ResponseMap;
import sdu.icat.pj.util.WebUtil;

@RestController
@Api(value="Group Controller",tags={"group"})
@RequestMapping("group")
public class GroupController {

    @Autowired private GroupService groupService;
    
    @ApiOperation(value="创建分组",notes="根据登录用户创建分组")
    @PostMapping("creation")
    public ResponseMap createGroup(@RequestBody Group group,HttpServletRequest request) {
	ResponseMap result = ResponseMap.newInstance();
	Long user = (Long)WebUtil.getCurrentUser(request);
	if(null==user) {
	    result.setFailedMap("no login", null);
	} else {
	    group.setId(user);
	    groupService.createGroup(group);
	    result.setSuccessMap("create success by user:"+user, group);
	}
	return result;
    }
    
    @ApiOperation(value="请求加入指定分组",notes="加入分组")
    @PostMapping("join")
    public ResponseMap joinGroup(long groupId,String context) {
	ResponseMap result = ResponseMap.newInstance();
	Group group = groupService.getOneGroup(groupId);
	if(group==null) {
	    result.setFailedMap("the group you request is uncreated now,please check it!", null);
	    return result;
	} else {
	    return groupService.requestJoin(group, context);
	}
    }
    
    @ApiOperation(value="允许加入")
    @PostMapping("allowJoin")
    public ResponseMap allowJoin(long groupRequestId) {
	ResponseMap result = ResponseMap.newInstance();
	if(groupService.commitRequest(groupRequestId)) {
	    result.setSuccessMap("同意加入",null);
	} else
	    result.setFailedMap("操作失败", null);
	return result;
    }
    
    @GetMapping("/first")
    @ApiOperation("第一个请求")
    public ResponseMap firstRes(HttpServletRequest request) {
	ResponseMap result = ResponseMap.newInstance();
	request.getSession().setAttribute("request Url", request.getRequestURL());  
	return result.setAttribute("requestUrl", request.getRequestURL());
    }

    @GetMapping("/session")
    @ApiOperation("获取会话")
    public ResponseMap sessions(HttpServletRequest request) {
	ResponseMap result = ResponseMap.newInstance();
	return result.setAttribute("sessionId", request.getSession().getId())
		.setAttribute("message", request.getSession().getAttribute("requestUrl"));
    } 
    
}
